package com.yingli.storage.net;

import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.yingli.storage.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class NetRequestActivity extends AppCompatActivity {

    private Button btnSave;
    private Button btnGetData;
    private static final String BASE_URL = "http://192.168.31.93:8081/";

    private EditText etName;
    private EditText etAge;

    private TextView tvResult;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_net_request);
        btnSave = findViewById(R.id.btn_save);
        btnGetData = findViewById(R.id.btn_get_data);
        etName = findViewById(R.id.et_name);
        etAge = findViewById(R.id.et_age);
        tvResult = findViewById(R.id.tv_result);
        btnSave.setOnClickListener(v -> {
            saveData();
        });
        btnGetData.setOnClickListener(v -> {
            getDataFromServer();
        });

    }

    private void getDataFromServer() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                HttpURLConnection connection = null;
                OutputStream outputStream = null;
                InputStream is = null;
                try {
                    URL url = new URL(BASE_URL + "list");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    /** 设置连接主机服务器超时时间：15000毫秒 */
                    connection.setConnectTimeout(15000);
                    /** 设置读取远程返回的数据时间：60000毫秒 */
                    connection.setReadTimeout(60000);
//                    connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                    connection.setRequestProperty("Content-Type", "application/json");
//                    outputStream.write(("name=" + URLEncoder.encode(etName.getText().toString(), "UTF-8") + "&age=" + URLEncoder.encode(etAge.getText().toString(), "UTF-8")).getBytes());
//                    outputStream.write(param.toString().trim().getBytes("UTF-8"));
                    connection.connect();
                    if (connection.getResponseCode() == 200) {
                        is = connection.getInputStream();
                        BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                        StringBuffer buffer = new StringBuffer();
                        String line = null;
                        while ((line = br.readLine()) != null) {
                            buffer.append(line);
                            buffer.append("\n\r");
                        }
                        runOnUiThread(() -> {
                            tvResult.setText(buffer);
                        });
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }  finally {
                    try {
                        if (is != null) {
                            is.close();
                        }
                        if (outputStream!=null){
                            outputStream.flush();
                            outputStream.close();
                        }
                        if (connection!=null){
                            connection.disconnect();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

    private void saveData() {
//        if (etName.getText().equals("")) {
//            Toast.makeText(this, "请输入名字", Toast.LENGTH_SHORT).show();
//            return;
//        }
        new Thread() {
            @Override
            public void run() {
                super.run();
                HttpURLConnection connection = null;
                OutputStream outputStream = null;
                InputStream is = null;
                try {
                    URL url = new URL(BASE_URL + "save");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("POST");
                    /** 设置连接主机服务器超时时间：15000毫秒 */
                    connection.setConnectTimeout(15000);
                    /** 设置读取远程返回的数据时间：60000毫秒 */
                    connection.setReadTimeout(60000);
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
//                    connection.setRequestProperty("Content-Type", "applicatio|n/json; charset=UTF-8");
                    //设置请求方式为form-data的形式提交数据
                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    //根据连接从服务器获取到输出流 此语句执行完毕后，已与服务器建立连接
                    outputStream = connection.getOutputStream();
//                    outputStream.write(("name=" + URLEncoder.encode(etName.getText().toString(), "UTF-8") + "&age=" + URLEncoder.encode(etAge.getText().toString(), "UTF-8")).getBytes());
//                    outputStream.write(param.toString().trim().getBytes("UTF-8"));
                    String param = "name="+etName.getText().toString()+"&age="+etAge.getText().toString();
                    outputStream.write(param.getBytes());
//
                    if (connection.getResponseCode() == 200) {
                        is = connection.getInputStream();
                        BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                        StringBuffer buffer = new StringBuffer();
                        String line = null;
                        while ((line = br.readLine()) != null) {
                            buffer.append(line);
                            buffer.append("\n\r");
                        }
                        runOnUiThread(() -> {
                            tvResult.setText(buffer);
                        });
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }  finally {
                    try {
                        if (is != null) {
                            is.close();
                        }
                        if (outputStream!=null){
                            outputStream.flush();
                            outputStream.close();
                        }
                        if (connection!=null){
                            connection.disconnect();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }
}
